<?php

namespace App\Models;

use App\Http\Models\User\UserBaseModel;
use Illuminate\Database\Eloquent\Model;

/**
 * App\Models\distribution
 *
 * @property int $id
 * @property int $buy_uid 购买人 订单分销效益生成者
 * @property int $beneficiary_uid 受益人id
 * @property string $order_sn 订单号
 * @property string $order_money 订单金额
 * @property string $total_money 受益金额
 * @property string $rate 分成比例
 * @property int $level 分销等级
 * @property int|null $created_at
 * @property int|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\distribution whereBeneficiaryUid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\distribution whereBuyUid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\distribution whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\distribution whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\distribution whereLevel($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\distribution whereOrderMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\distribution whereOrderSn($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\distribution whereRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\distribution whereTotalMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\distribution whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class distribution extends Model
{
    public $table       = 'distribution';
    public $timestamps  = false;

    /**
     * 我的收益
     * @param $uid
     * @return array|\Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public static function getMyBenefitList($uid)
    {
        $data = self::where('beneficiary_uid',$uid)
            ->join('user as u1','u1.id','=','distribution.buy_uid')
            ->join('user as u2','u2.id','=','distribution.beneficiary_uid')
            ->select('u1.user_name as buy_user_name','u2.user_name as beneficiary_user_name','u1.user_nickname as buy_user_nickname','u2.user_nickname as beneficiary_user_nickname','distribution.*')
            ->paginate(15);
        if (!empty($data)){
            $data = $data->toArray();
        }else{
            $data = [];
        }
        return $data;
    }


    /**
     * 我的贡献
     * @param $uid
     * @return array|\Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public static function getMyDevoteList($uid)
    {
        $data = self::where('buy_uid',$uid)
            ->join('user as u1','u1.id','=','distribution.buy_uid')
            ->join('user as u2','u2.id','=','distribution.beneficiary_uid')
            ->select('u1.user_name as buy_user_name','u2.user_name as beneficiary_user_name','u1.user_nickname as buy_user_nickname','u2.user_nickname as beneficiary_user_nickname','distribution.*')
            ->paginate(15);
        if (!empty($data)){
            $data = $data->toArray();
        }else{
            $data = [];
        }
        return $data;
    }


    public static function addDistributionRecord($data)
    {
        $flag = self::insert($data);
        return $flag;
    }


    /**计算该用户任意层级的已完成订单和未完成订单收益
     * @param $uid     int  需要计算收益的用户
     * @param $level   mixed  于与该用户关联的分销层级
     * @return array
     */
    public function api_my_benefit_total($uid,$level)
    {
        if(!is_array($level) && !is_numeric($level)){
            return [];
        }

        $level = is_numeric($level) ? [$level] : $level;
        $query = self::query()->where('beneficiary_uid','=',$uid);
            $query -> where(function($query) use($level){
                foreach($level as $val){
                    $query -> orwhere('level','=',$val);
                }
            });

        $query_1                = clone $query;
        $query_2                = clone $query;

        $order_finish_money     = $query_1->where('status',1)->sum('total_money');
        $order_not_finish_money = $query_2->where('status',0)->sum('total_money');

        return [
           'finished_order_money'    => $order_finish_money,
           'unfinished_order_money' => $order_not_finish_money
        ];
    }
    
    
    
    public static function myDistributionCenter($uid)
    {
        #结算收益：
        $finished_order_money                       = self::where('status',1)
                                                                 ->where('beneficiary_uid',$uid)
                                                                 ->sum('total_money');
        $order_not_finish_money                     = self:: where('status',0)
                                                                ->where('beneficiary_uid',$uid)
                                                                ->sum('total_money');
        #可提现佣金：
        $rebateMoney                                = UserBaseModel::getUser ($uid);
        $rebateMoney                                = $rebateMoney['withdraw']??0;
        #累计客户
        #累计邀请
        $invitingCount                              = UserBaseModel::where ('BNF_Lv1',$uid)->count('id');
        #推广订单
            #1 获取用户的 受邀请人 的 uid 集合
        $uids                                       = UserBaseModel::where ('BNF_Lv1',$uid);
        if (!empty($uids)){
                $uids                               = get_object_vars($uids);
                $advertisingOrderCount              = Order::whereIn  ('user_id',$uids)->count();
        }else{
            $advertisingOrderCount                  = 0;
        }

        $total                                      = $finished_order_money +$order_not_finish_money;
        $total                                      = sprintf('%.2f',$total);
        $rebateMoney                                = sprintf('%.2f',$rebateMoney);
        $order_not_finish_money                     = sprintf('%.2f',$order_not_finish_money);
        $finished_order_money                       = sprintf('%.2f',$finished_order_money);
        return ['finished_order_money'             =>$finished_order_money,
            'order_not_finish_money'                =>$order_not_finish_money,
            'rebateMoney'                           =>$rebateMoney,'invitingCount'=>$invitingCount,
            'advertisingOrderCount'                 =>$advertisingOrderCount,
            'total'                                 =>$total
        ];
    }







}
